package a日常研究._03java线程._01生产者消费者模型;

import a日常研究._03java线程._01生产者消费者模型.base.BasePCModel;

/**
 * 单个生产者，单个消费者
 */
public class SinglePCModel extends BasePCModel {
    private static final Object lock = new Object();

    public static void main(String[] args) {
        new SinglePCModel().testSinglePCUseObjectLock();
    }

    /**
     * 单个生产者，单个消费者，使用对象锁
     */
    public void testSinglePCUseObjectLock() {
        Thread p = new Thread(() -> {
            // 生产
            try {
                while (true) {
                    synchronized (lock) {
                        if (queue.size() == FULL_NUM) {
                            lock.wait();
                        }
                        produce();
                        lock.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread c = new Thread(() -> {
            // 消费
            try {
                while (true) {
                    synchronized (lock) {
                        if (queue.isEmpty()) {
                            lock.wait();
                        }
                        consume();
                        lock.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        p.start();
        c.start();
    }
}
